#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include "fifo.h"
#include "chat_sig.h"

void *fifo_read(void *);
void *fifo_write(void *);

int main()
{
	struct sigaction sigint_handler;
	pthread_t thread_reader;
    	pthread_t thread_writer;

	system("clear");	
	printf ("---------------------------------------------\n");
	printf ("=== Welcome to this tiny chat application ===\n");
	printf ("---         To exit press Crl+C           ---\n");
	printf ("---------------------------------------------\n");

	sigint_handler.sa_handler = cleanup;
	sigemptyset(&sigint_handler.sa_mask);
	sigint_handler.sa_flags = 0;
	sigaction(SIGINT, &sigint_handler, NULL);

    if (open("chatlock", O_RDONLY | O_CREAT | O_EXCL, 0600) >= 0) {
            pthread_create(&thread_reader, NULL, fifo_read, (void*)"fifo_client2");
            pthread_create(&thread_writer, NULL, fifo_write, (void*)"fifo_client1");
            pthread_join(thread_reader, NULL);
            pthread_join(thread_writer, NULL);
    } else {
            pthread_create(&thread_reader, NULL, fifo_read,  (void*)"fifo_client1");
            pthread_create(&thread_writer, NULL, fifo_write, (void*)"fifo_client2");
            pthread_join(thread_reader, NULL);
            pthread_join(thread_writer, NULL);
    }

    return 0;
}


